import React, { useEffect, useState } from 'react';
import {
  Form,
  Row,
  Col,
  Button,
  Table,
  Select,
  DatePicker,
  message,
  Input,
  Modal,
} from 'antd';
import {
  UserEdit,
  UserEditObject,
} from '@/pages/teacher/work/arrangement/workEdit';
import { PlusOutlined } from '@ant-design/icons';
import request from '@/http';

interface ItemProps {
  label: string;
  value: string;
}

export default () => {
  const [pagination, setPagination] = useState({
    current: 1,
    total: 5,
    pageSize: 5,
    showSizeChanger: true,
    pageSizeOptions: ['5', '10', '20', '30'],
    showQuickJumper: true,
  });

  const [dataSource, setDataSource] = useState([]);

  const [formObject] = Form.useForm();
  const [loading, setLoading] = useState(true);

  const [
    currentEditObject,
    setCurrentEditObject,
  ] = React.useState<UserEditObject>({
    isModalVisible: false,
  });

  const loadDataSource = async (
    userParams: any,
    pageValue: any,
    pageSizeValue: any,
  ) => {
    try {
      const result: any = await request.post(
        '/api/teacher/Task/QueryJob',
        {
          current: 0,
          size: 0,
        },
        {
          headers: {
            'Content-Type': 'application/json',
          },
        },
      );
      const newPageObject = {
        ...pagination,
        current: pageValue,
        pageSize: pageSizeValue,
        total: result.records, //总条数 分页
      };
      if (result.message === '成功') {
        const data = result.data.info.map((user: any) => ({
          key: user.id,
          completeDate: user.completeDate,
          courseName: user.courseName,
          createTime: user.createTime,
          current: user.current,
          size: user.size,
          teacherName: user.teacherName,
          teamName: user.teamName,
          title: user.title,
          total: user.total,
          tobeApproved: user.tobeApproved,
          tobeSubmitted: user.tobeSubmitted,
          approved: user.approved,
          workType: user.workType,
        }));
        setPagination(newPageObject);
        setLoading(false);
        setDataSource(data);
      }
    } catch (e) {
      message.error('数据错误');
    }
  };

  useEffect(() => {
    loadDataSource(null, 1, pagination.pageSize);
    selectDataSource();
  }, []);

  const pageOnChange = async (page: any) => {
    await loadDataSource(
      formObject.getFieldsValue(),
      page.current,
      page.pageSize,
    );
  };

  const [ModalVisible, setModalVisible] = useState(false);

  //删除功能
  const deleteRow = (row: any) => {
    setModalVisible(true);
    localStorage.setItem('deleteRow', row.key);
  };
  const handleOk = async () => {
    const rows = localStorage.getItem('deleteRow');
    const result: any = await request.delete(
      '/api/teacher/Task/DeleteJob/{id}' + rows,
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } },
    );
    setModalVisible(false);
    loadDataSource(null, 1, pagination.pageSize);
  };

  const handleCancel = () => {
    setModalVisible(false);
  };

  const columns = [
    {
      title: '发布日期',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '项目名称',
      dataIndex: 'courseName',
      key: 'courseName',
    },
    {
      title: '作业主题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '作业类型',
      key: 'workType',
      dataIndex: 'workType',
    },
    {
      title: '实训老师',
      key: 'teacherName',
      dataIndex: 'teacherName',
    },
    {
      title: '计划完成时间',
      key: 'completeDate',
      dataIndex: 'completeDate',
    },
    {
      title: '小组',
      key: 'teamName',
      dataIndex: 'teamName',
    },
    {
      title: '学生总数',
      dataIndex: 'total',
      key: 'total',
    },
    {
      title: '待提交',
      dataIndex: 'tobeSubmitted',
      key: 'tobeSubmitted',
    },
    {
      title: '待批复',
      dataIndex: 'tobeApproved',
      key: 'tobeApproved',
    },
    {
      title: '已批复',
      dataIndex: 'approved',
      key: 'approved',
    },
    {
      title: '操作',
      key: 'action',
      render: (row: any) => (
        <>
          <Button
            type="link"
            onClick={() => {
              setCurrentEditObject({
                ...row,
                isModalVisible: true,
              });
            }}
          >
            查看
          </Button>
          <Button
            type="link"
            onClick={() => {
              deleteRow(row);
            }}
          >
            删除
          </Button>
        </>
      ),
    },
  ];

  const [courseName, setCourseName] = useState([]);
  const [groupName, setGroupName] = useState([]);
  const [teacherName, setTeacherName] = useState([]);

  const selectDataSource = async () => {
    const dataCourseName = await request.post(
      '/api/common_module/a_t_s/getCourse',
    );
    setCourseName(dataCourseName.data);
    const dataGroupName = await request.post(
      '/api/common_module/a_t_s/getTeam',
    );
    setGroupName(dataGroupName.data);
    const dataTeacherName = await request.post(
      '/api/common_module/a_t_s/getTeacher',
    );
    setTeacherName(dataTeacherName.data);
  };

  //查询功能
  const selectWork = async () => {
    const data = await formObject.getFieldsValue();
    try {
      const result: any = await request.post(
        '/api/teacher/Task/QueryJob',
        {
          current: 0,
          size: 0,
          createTime: data.createTime
            ? data.createTime.format('YYYY-MM-DD HH:mm')
            : '',
          completeDate: data.completeDate
            ? data.completeDate.format('YYYY-MM-DD HH:mm')
            : '',
          courseName: data.courseName,
          title: data.title,
          teamName: data.teamName,
          workType: data.workType,
          teaName: data.teacherName ? data.teacherName.toString() : '',
        },
        {
          headers: {
            'Content-Type': 'application/json',
          },
        },
      );
      if (result.data.info.length == 0) {
        message.error('暂无数据');
        setDataSource(result.data.info);
      } else {
        setDataSource(result.data.info);
      }
    } catch (e) {
      //message.error('数据错误');
    }
  };

  /*重置搜索框*/
  const resetWork = () => {
    formObject.resetFields();
    loadDataSource(null, 1, pagination.pageSize);
  };

  const formItemLayout = {
    labelCol: {
      span: 8,
    },
    wrapperCol: {
      span: 24,
    },
  };

  return (
    <>
      <Form form={formObject} {...formItemLayout}>
        <Row gutter={24} wrap={false} style={{ width: '100%' }}>
          <Col span={6}>
            <Form.Item name="createTime" label="发布时间">
              <DatePicker
                style={{ width: '100%' }}
                placeholder="请选择查询日期"
              />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="courseName" label="项目名称">
              <Select style={{ width: '100%' }} placeholder="请选择">
                {(courseName || []).map((courseName: any) => {
                  return (
                    <option
                      key={courseName.courseId}
                      value={courseName.courseName}
                    >
                      {courseName.courseName}
                    </option>
                  );
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="title" label="作业主题">
              <Input placeholder="请输入.." />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="teacherName" label="实训老师">
              <Select
                mode="tags"
                style={{ width: '100%' }}
                placeholder="请选择"
              >
                {(teacherName || []).map((teacherName: any) => {
                  return (
                    <option
                      key={teacherName.teacherId}
                      value={teacherName.teacherName}
                    >
                      {teacherName.teacherName}
                    </option>
                  );
                })}
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24} wrap={false} style={{ width: '100%' }}>
          <Col span={6}>
            <Form.Item name="completeDate" label="计划完成时间">
              <DatePicker
                style={{ width: '100%' }}
                placeholder="请选择查询日期"
              />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="teamName" label="小组">
              <Select style={{ width: '100%' }} placeholder="请选择">
                {(groupName || []).map((groupName: any) => {
                  return (
                    <option key={groupName.teamId} value={groupName.teamName}>
                      {groupName.teamName}
                    </option>
                  );
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="workType" label="作业类型">
              <Select style={{ width: '100%' }} placeholder="请选择">
                <option key="0" value="0">
                  平时作业
                </option>
                <option key="1" value="1">
                  阶段性作业
                </option>
                <option key="2" value="2">
                  最终交互作业
                </option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={6}>
            <Button type="primary" onClick={selectWork}>
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={resetWork}>
              重置
            </Button>
          </Col>
        </Row>
        <Form.Item>
          <Button
            type="primary"
            onClick={(row) => {
              setCurrentEditObject({
                ...row,
                isModalVisible: true,
              });
            }}
          >
            <PlusOutlined />
            新增
          </Button>
        </Form.Item>
      </Form>
      <Table
        columns={columns}
        loading={loading}
        dataSource={dataSource}
        scroll={{ x: 1500 }}
        pagination={pagination}
        onChange={pageOnChange}
      />
      <Modal
        visible={ModalVisible}
        title="删除作业任务"
        cancelText="取消"
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form.Item name="请确认是否删除该条作业任务?">
          <label>删除后，学生将无法查看该条作业任务，也无法进行作业提交</label>
        </Form.Item>
      </Modal>
      <UserEdit
        editObject={currentEditObject}
        //onClose={loadDataSource}
      ></UserEdit>
    </>
  );
};
